package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.model.content.ext.liftTarget
import com.gitee.wsl.doc.prosemirror.model.node.ext.canSplit
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.TextSelection
import com.gitee.wsl.doc.prosemirror.transform.ext.lift
import com.gitee.wsl.doc.prosemirror.transform.ext.split


object LiftEmptyBlock: Command {

    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val textSelection = state.selection as? TextSelection ?: return false
        val cursor = textSelection._cursor

        // 检查光标是否存在且父节点内容为空
        if (cursor == null || cursor.parent.content.size > 0) return false

        // 如果深度大于1且不在父节点末尾，尝试分割
        if (cursor.depth > 1 && cursor.after() != cursor.end(-1)) {
            val before = cursor.before()
            if (state.doc.canSplit( before)) {
                if (dispatch != null) {
                    dispatch(state.tr.split(before).scrollIntoView())
                }
                return true
            }
        }

        // 尝试提升块
        val range = cursor.blockRange()
        val target = range?.liftTarget()

        if (target == null) return false

        if (dispatch != null && range != null) {
            dispatch(state.tr.lift(range, target).scrollIntoView())
        }

        return true
    }

}

/**
 * 提升空块命令
 * 如果光标在可以提升的空文本块中，则提升该块
 */
val Command.Companion.liftEmptyBlock: Command get() = LiftEmptyBlock
